# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

from coin.exchange.base.kr_rest.currency import NativeCurrency
from coin.exchange.base.kr_rest.currency_constants import (
    BCHABC_BCHSV_FORK_TIME,
    BCHA_BCHN_FORK_TIME)
from coin.exchange.kraken.kr_rest.constants import (currency_list, native_currency_list)


def validate_native_currency(currency):
  assert type(currency) == str, str(currency)
  assert currency.upper() == currency
  assert currency in currency_list, currency


def from_native_currency(native_currency_str, current_datetime):
  validate_native_currency(native_currency_str)
  if native_currency_str == 'XBT':
    currency_str = 'BTC'
  elif native_currency_str == 'BSV':
    assert current_datetime >= BCHABC_BCHSV_FORK_TIME, current_datetime
    currency_str = 'BCHSV'
  elif native_currency_str == 'BCH':
    if current_datetime < BCHABC_BCHSV_FORK_TIME:
      currency_str = 'BCH'
    elif BCHABC_BCHSV_FORK_TIME <= current_datetime < BCHA_BCHN_FORK_TIME:
      currency_str = 'BCHABC'
    else:
      currency_str = 'BCHN'
  elif native_currency_str == 'BCHA':
    assert BCHA_BCHN_FORK_TIME <= current_datetime
    currency_str = 'BCHA'
  else:
    currency_str = native_currency_str
  return currency_str


def to_native_currency(currency):
  assert currency not in ('XBT', 'BSV'), currency
  if currency == 'BTC':
    native_currency = 'XBT'
  elif currency == 'BCHSV':
    native_currency = 'BSV'
  elif currency in ('BCHABC', 'BCHN'):
    native_currency = 'BCH'
  else:
    native_currency = currency
  validate_native_currency(native_currency)
  return native_currency


def remove_native_currency_prefix(native_currency):
  """
  Convert native_currency with prefix to native_currency without prefix.
  XXRP -> XRP, XXBT -> XBT """
  name_map = dict(native_currency_list)
  assert (native_currency in list(name_map.keys())), native_currency
  return name_map[native_currency]


class KrakenCurrency(NativeCurrency):
  _exchange = "Kraken"

  def __init__(self, currency, native_currency):
    assert to_native_currency(currency) == native_currency, (currency, native_currency)
    super().__init__(currency, native_currency)

  @classmethod
  def FromStrCurrencyImpl(cls, currency_str, current_datetime):
    return cls(currency_str, to_native_currency(currency_str))

  @classmethod
  def FromStrNativeCurrencyImpl(cls, native_currency_str, current_datetime):
    return cls(from_native_currency(native_currency_str, current_datetime),
               native_currency_str.upper())
